<template>
    <div class="app-container">
        <!-- <el-form :model="params" ref="queryForm" size="small" :inline="true" label-width="120px"> -->
        <!-- <el-form-item label="班级" prop="classId">
                <el-input v-model="params.stuName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item> -->
        <!-- <el-form-item label="年级" prop="gradeId">
                <el-select v-model="params.gradeId" placeholder="请选择年级" filterable clearable>
                    <el-option v-for="(v, i) in gradeList" :key="i" :label="v.gradeName" :value="v.gradeId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学生姓名" prop="stuName">
                <el-input v-model="params.stuName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="学号" prop="stuNo">
                <el-input v-model="params.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
               <el-button icon="el-icon-upload2" size="mini" @click="confirmVClick">费用记录发起确认</el-button>
            </el-form-item> -->
        <!-- </el-form> -->

        <el-button type="primary" icon="el-icon-search" size="mini" @click="getDormitory">查询</el-button>
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <div style="margin-top: 20px; display: flex;" class="main">
            <el-table v-loading="loading" :data="dormitoryList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="宿舍" align="center" prop="roomNo" width="300">
                    <template slot-scope="scope">
                        {{ scope.row.campusName + " " + scope.row.parkName + " " + scope.row.buildingName + " " +
            scope.row.roomNo + "(" + scope.row.gender + ")" }}
                    </template>
                </el-table-column>
                <el-table-column label="分配班级" align="center" prop="className" />
                <el-table-column label="宿舍床位数量" align="center" prop="bedNum" />
                <el-table-column label="分配到的床位数量" align="center" prop="bedCount" />
                <el-table-column label="是否开放给新生宿舍确认" align="center">
                    <template slot-scope="scope">
                        <el-switch :disabled="scope.row.isMixed == 1" @change="changeRoomIsMixed(scope.row)"
                            v-model="scope.row.isMixed" active-text="是" inactive-text="否" active-color="#13ce66"
                            inactive-color="#ff4949" active-value="1" inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="lookIn(scope.row)"
                            icon="el-icon-view">查看入住新生</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getDormitory" />

        <el-dialog title="查看已经入住新生" :visible.sync="lookV" width="">
            <el-button size="mini" @click="addVClick" class="btn-blue">添加新生</el-button>
            <el-table :data="stu_list">
                <el-table-column label="学生姓名" align="center" prop="xsxm" />
                <el-table-column label="考生号" align="center" prop="ksh" />
                <el-table-column label="专业" align="center" prop="zy" />
                <el-table-column label="班级" align="center" prop="zy" />
                <el-table-column label="性别" align="center" prop="xb" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="cancel(scope.row)"
                            icon="el-icon-close">撤销</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <el-dialog title="添加新生" :visible.sync="addV" width="1200px">
            <el-form label-width="90px" :inline="true">
                <el-form-item label="民族">
                    <el-input size="mini" v-model="add_mz" clearable />
                </el-form-item>
                <el-form-item label="生源地">
                    <el-input size="mini" v-model="add_syd" clearable />
                </el-form-item>
                <el-form-item label="户籍所在地">
                    <el-input size="mini" v-model="add_sfz_addr" clearable />
                </el-form-item>
                <el-form-item label="">
                    <el-button size="mini" @click="listClassStu">搜索</el-button>
                </el-form-item>
            </el-form>
            <el-button size="small" @click="doAdd">添加</el-button>
            <el-table @selection-change="handleAddSelectionChange" border
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                :data="add_stu_list.slice((currentPage - 1) * pagesize, currentPage * pagesize)" :stripe="true"
                :current-page.sync="currentPage" max-height="550" style="width: 100%">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="ksh" label="考生号" width="180" />
                <el-table-column prop="xsxm" label="学生姓名" />
                <el-table-column prop="xb" label="性别" width="50" />
                <el-table-column prop="dorm" label="宿舍" width="280" />
                <el-table-column prop="mz" label="民族" />
                <el-table-column prop="syd" label="生源地">
                </el-table-column>
                <el-table-column prop="sfzAddr" label="户籍所在地">
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[10, 15, 20]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
                :total="add_total" v-if="add_total != 0">
            </el-pagination>
        </el-dialog>
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <div class="template-download">
                        <span class="red-text">如果没有导入宿舍数据的模版那先请</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate">下载模板</el-link>
                    </div>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { cancelReg, addReg, listFdyRoom, allocate, unbindDor, changeRoomIsMixed, getRegByRoom, listClassCanStu } from '@/api/dormitory/dormitory-assignment/school-number';
import { fullLoading, isEmpty } from "@/api/helpFunc";
import { getToken } from '@/utils/auth'
export default {
    name: 'SRSUiDormitoryBedView',
    data() {
        return {
            // 专业人数列表
            majorGenderList: [],
            // 单元列表
            unitList: [],
            floorList: [],
            // 参数
            queryParams: {
                buildingId: this.$route.query.buildingId,
                floorId: null,
                unitId: null,
                pageSize: 10,
                pageNum: 1,
            },
            dormitoryList: [],
            loading: false,
            classCode: "",
            total: 0,
            dormIds: [],
            // 是否将床宿舍分配完毕
            isGenderAssigned: false,
            gender: "男",

            lookV: false,

            stu_list: [],

            addV: false,
            now_room: {},
            add_stu_list: [],

            addForm: {
                stuList: [],
                dormitoryId: null
            },

            currentPage: 1,
            pagesize: 10,
            add_total: 0,

            temp_data: [],

            add_mz: null,
            add_syd: null,
            add_sfz_addr: null,
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                //  上传的地址
                url: process.env.VUE_APP_BASE_API + '/dormitory/dms-dormitory-class/importData',
            },
        };
    },

    mounted() {
        this.getDormitory();
    },

    methods: {
        handleSizeChange(val) {
            this.pagesize = val;
        },
        handleCurrentChange(val) {
            this.currentPage = val;
        },

        async cancel(val) {
            let sdata = {
                dormitoryId: this.now_room.id,
                ksh: val.ksh
            };

            this.$confirm('此操作将撤销该生宿舍分配, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let loading = fullLoading(this);
                let res = await cancelReg(sdata);
                loading.close();
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '撤销成功!'
                    });
                    this.getRegByRoom();
                }


            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });

        },
        async doAdd() {
            let sdata = { ...this.addForm };
            console.log(sdata);
            if (isEmpty(sdata.stuList)) {
                this.$message.info("请选择学生");
                return;
            }
            this.$confirm('此操作将覆盖学生已有的宿舍分配, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let loading = fullLoading(this);
                let res = await addReg(sdata);
                loading.close();
                if (res.code == 200) {
                    this.getRegByRoom();
                    this.listClassStu();
                    this.$message.success(res.msg);
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });

        },
        async addVClick() {
            await this.listClassStu();
            this.addV = true;
        },
        async listClassStu() {
            this.temp_data = [];
            this.add_stu_list = [];
            let loading = fullLoading(this);
            let params = {
                BJDM: this.now_room.classCode,
                MZ: this.add_mz,
                SYD: this.add_syd,
                sfzAddr: this.add_sfz_addr
            }
            let res = await listClassCanStu(params);
            loading.close();
            if (res.code == 200) {
                this.temp_data = [...res.data];
                this.add_stu_list = [...res.data];
                this.add_total = this.add_stu_list.length;
            }
        },
        async fastAllot() {

        },
        async getRegByRoom() {
            let loading = fullLoading(this);
            let res = await getRegByRoom(this.addForm.dormitoryId);
            loading.close();
            if (res.code == 200) {
                this.stu_list = [...res.data];
            }
        },
        async lookIn(room) {
            this.now_room = { ...room };
            this.addForm.dormitoryId = room.id;
            await this.getRegByRoom();
            this.lookV = true;
        },

        async changeRoomIsMixed(room) {
            this.$confirm('开启后就不能再关闭，您真的要这么做吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let sdata = {
                    dormitoryId: room.id,
                    bjdm: room.classCode,
                    isMixed: room.isMixed
                };
                let loading = fullLoading(this);
                let res = await changeRoomIsMixed(sdata);
                loading.close();
                if (res.code == 200) {
                    this.$message.success(res.msg);
                }
            }).catch(() => {
                room.isMixed = '0';
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });



        },

        getDormitory() {
            this.loading = true;
            listFdyRoom(this.queryParams).then(res => {
                this.total = res.total;
                this.dormitoryList = res.rows;
                this.loading = false;
                console.log(res)
            });
        },
        // 获取楼层id
        selectFloor(id) {
            this.queryParams.unitId = null
            if (this.queryParams.floorId == id) {
                this.queryParams.floorId = null
            } else {
                this.queryParams.floorId = id
            }
            this.getDormitory()
        },
        // 分配宿舍
        distributeDormitory() {
            if (this.dormIds.length && this.classCode) {
                // if (!this.isGenderAssigned) {
                //     return this.$message.error(`该班级${this.gender}生已经分配完毕`)
                // }
                allocate({ dormitoryIds: this.dormIds, bjdm: this.classCode, gender: this.gender }).then(res => {
                    this.getDormitory()
                    if (res.code == 200) {
                        this.$message.success('分配成功');
                    }
                })
            } else {
                this.$message.warning('请先选择好需要分配的专业或宿舍');
            }
        },
        selectClass(code, gender) {
            // gender.forEach(item => {
            //     if (item.bedSelected == item.count) {
            //         this.isGenderAssigned = true
            //     }else{
            //         this.isGenderAssigned = false
            //     }
            // })
            this.classCode = code
        },
        // 选择宿舍
        selectDormitory(id) {
            if (!this.dormIds.includes(id)) return this.dormIds.push(id);
            // 删除重复的id
            this.dormIds = this.dormIds.filter(item => item !== id)

        },
        // 返回选中状态
        isSelected(id) {
            return this.classCode.includes(id)
        },

        handleAddSelectionChange(selection) {
            this.addForm.stuList = selection.map(item => item);
        },

        // 多选框数据
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.dormIds = selection.map(item => item.id)
        },
        // 取消绑定某宿舍
        unbindDormitory() {
            if (!this.dormIds.length) {
                this.$message.warning("请先选择需要解除绑定的宿舍")
            } else {
                unbindDor(this.dormIds).then(res => {
                    if (res.code == 200) {
                        this.$message.success("解除绑定成功!")
                        this.getDormitory()
                        this.getMajorGenderNumber()
                    }
                })
            }
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                '/dormitory/dms-dormitory-class/import',
                {
                    ...this.queryParams,
                },
                `宿舍数据导出.xlsx`
            )
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = '宿舍数据导入'
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('/dormitory/dms-dormitory-class/importTemplate', {}, '宿舍导入模板.xlsx')
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
            this.getList()
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit()
        },
    },
    filters: {
        filterState(value) {
            if (!value) return "已分配"
            return "待分配"
        },
        filterUnit(value) {
            if (value == 'default') return "默认单元"
            return value
        },
        filterClass(value) {
            if (!value) return "暂无班级"
            return value
        }
    }
};
</script>

<style lang="scss" scoped>
.top {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20px;

    .box-card {
        min-width: 180px;
        margin-right: 20px;
        min-height: 100px;
    }
}

.unit {
    display: flex;
    flex-wrap: wrap;
}

.main {
    .box-card {
        width: 180px;
    }
}

.floor {
    display: flex;
    flex-direction: column;
    width: 90px;
}

.condition-selection {
    margin-top: 20px;
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

#active,
.active {
    box-shadow: 0px 0px 8px 2px rgba(0, 120, 255, 0.5);
}

.template-download {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}

.red-text {
    color: red;
}
</style>
